import { ref } from "vue";
import L from "leaflet";
import "leaflet/dist/leaflet.css";

let map = null;
export const initMap = () => {
    if (map == null) {
        map = L.map(container, {
            zoom: 18,
            maxZoom: 18,
            zoomControl: false,
        });

        let Url =
            "http://wprd04.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}";

        L.tileLayer(Url, {
            attribution: "派软",
        }).addTo(map);
    }
};

let PiIcon = L.icon({
    iconUrl: "/images/map/marker.png",
    className: "blue-icon",
    iconSize: [28, 50],
    iconAnchor: [14, 25],
    html: "广州番禺店",
});

export const moveTarget = (coords) => {
    map.setView(coords, 18);
    L.marker(coords, {
        icon: PiIcon,
    }).addTo(map);
};

let dis = ref(null);
let events = null;

export const getLocation = () => {
    map.locate({
        maxZoom: 18,
    });
    return new Promise((resolve, reject) => {
        map.on("locationfound", function(e) {
            events = e;
            resolve(e);
        });
    });
};

export const getDistance = (coords) => {
    // let e = await getLocation();
    let latlng = L.latLng(events.latitude, events.longitude);
    let latlng2 = L.latLng(coords);
    let distance = map.distance(latlng, latlng2);
    distance = parseInt(distance);
    dis.value =
        distance < 1000 ? distance + "m" : parseInt(distance / 1000) + "km";
    return distance < 1000 ? distance + "m" : parseInt(distance / 1000) + "km";
};

export { dis };